package com.fastjars.business.shiro.filter;

import com.fastjars.business.shiro.TokenHolder;
import com.fastjars.business.shiro.model.UserModel;
import com.fastjars.business.spring.http.Resp;
import org.apache.commons.util.RequestUtils;
import org.apache.commons.util.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.SessionKey;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.support.DefaultSubjectContext;
import org.apache.shiro.web.filter.authc.AuthenticationFilter;
import org.apache.shiro.web.session.mgt.WebSessionKey;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

/**
 * ValidLoginFilter
 * 校验用户TOKEN是否存在
 * @author Brant Liu <br>
 * 邮箱：lbf1988@qq.com <br>
 * 日期：2018/5/9
 * @version 1.0.0
 */
public class ValidLoginFilter extends AuthenticationFilter {
    public static final String TOKEN_KEY = "token";

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        UserModel userCert = TokenHolder.getToken();
        boolean shiroSubject = super.isAccessAllowed(request, response, mappedValue);
        String token = ((HttpServletRequest) request).getHeader(TOKEN_KEY);
        if((!StringUtils.isBlank(token) && null != getCurrentThreadToken(token,request,response)) || shiroSubject || !StringUtils.isBlank(userCert)){
            return true;
        }
        return false;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        // TODO: 2018/5/9 保存当前Request信息
        super.saveRequest(servletRequest);
        // TODO: 2018/5/9 Ajax请求处理
        if(RequestUtils.isAjaxRequest((HttpServletRequest) servletRequest)){
            WriterUtils.write(servletResponse, Resp.notLogin().build().toJsonString());
            return false;
        }
        // TODO: 2018/5/9 非Ajax跳转到登录页面
        super.redirectToLogin(servletRequest, servletResponse);
        return false;
    }

    public UserModel getCurrentThreadToken(String sessionId, ServletRequest request, ServletResponse response) {
        try {
            SessionKey sessionKey = new WebSessionKey(sessionId, request, response);
            Session session = SecurityUtils.getSecurityManager().getSession(sessionKey);
            SimplePrincipalCollection principalCollection = (SimplePrincipalCollection) session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
            return (UserModel) principalCollection.getPrimaryPrincipal();
        }catch (Exception ex){

        }
        return null;
    }
}
